package com.books.controller.login_regis;

/**
 * @author ZhouRui
 * @title: 码上就来
 * @projectName cbstore-spring-boot
 * @description: TODO
 * @date 2021/10/2520:27
 */

import com.baidu.aip.face.AipFace;
import com.books.model.bo.Result;
import com.books.model.entity.login_regis.UserLogin;
import com.books.service.login_regis.IUserLoginService;
import com.books.service.login_regis.IUserRegisService;
import com.books.service.people.IPeopleService;
import org.springframework.util.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;


@RestController
@RequestMapping(method = RequestMethod.GET)
public class FaceRegisterController {

    //设置APPID/AK/SK
    public static final String APP_ID = "25052355";
    public static final String API_KEY = "gjWoV5v9hT3kbsM6sVphvmWf";
    public static final String SECRET_KEY = "sDUFQUVrAQF7PZwpvErmo6US5p1SWOyS";

    @Autowired
    private IUserLoginService userLoginService;

    @Autowired
    private IUserRegisService userRegisService;

    @Autowired
    private IPeopleService peopleService;

    @PostMapping(value = "faceregister")
    public Result register(String userName, String faceBase, String date, String phone) throws IOException {
        Integer code;
        if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(faceBase)) {
            //文件上传的地址
            String upPath = "src\\main\\webapp\\face";
            //用于查看路径是否正确
            System.out.println(upPath);
            // 图片名称
            String fileName = userName + System.currentTimeMillis() + ".png";
            System.out.println(upPath + "\\" + fileName);
            File file = new File(upPath + "\\" + fileName);
            //初始化百度云的AipFace
            AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
            //往自己demo数据库里插入一条用户数据
            UserLogin userLogin = new UserLogin();
            userLogin.setUname(userName);
            userLogin.setAccount(phone);
            userLogin.setPassword("face"+System.currentTimeMillis());
            userLogin.setFace(upPath + "\\" + fileName);
            userLogin.setRegisdate(date);
            UserLogin exitUser = userLoginService.loginByUname(userName);
            if (exitUser ==null) {
                exitUser=userLoginService.loginByAccount(phone);
                if(exitUser ==null){
                    //向百度云人脸库插入一张人脸
                    code=facesetAddUser(client, faceBase, phone);
                    if(code==0){
                        // 往自己demo服务器里面上传摄像头捕获的图片
                        GenerateImage(faceBase, file);
                        userRegisService.registration(userLogin);
                        userRegisService.regisuseradd(userLogin);
                        return new Result("200","注册成功",userLogin.getPassword());
                    }
                    return new Result("300","识别失败");
                }
                else {
                    return new Result("500","该手机号已经注册过！");
                }
            }
            else {
                return new Result("500","该用户名已经注册过！");
            }
        }
        return new Result("505","未知失败");
    }

    @PostMapping(value = "falogin")
    public String login(String faceBase, String uname, HttpServletRequest request) {
        HttpSession session=request.getSession();
        if(peopleService.getPeopleByAccount(uname)!=null){
            session.setAttribute("people",peopleService.getPeopleByAccount(uname));
            session.setAttribute("user",userLoginService.loginByAccount(uname));
        }
        String faceData = faceBase;
        //进行人像数据对比
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        Double num = verifyUser(faceData, client);
        if (num > 95) {
            return "1";
        } else {
            return "2";
        }

    }

    /**
     * 人脸比对
     *
     * @param imgBash64 照片转bash64格式
     * @return
     */
    public Double verifyUser(String imgBash64, AipFace client) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        JSONObject res = client.search(imgBash64, "BASE64", "test", options);
        System.out.println(res.toString(2));
        System.out.println(res.getJSONObject("result"));
        System.out.println(res.getJSONObject("result").getJSONArray("user_list"));
        JSONObject user = (JSONObject) res.getJSONObject("result").getJSONArray("user_list").get(0);
        Double score = (Double) user.get("score");
        return score;
    }


    /**
     * @param @param  imgStr
     * @param @param  imgFilePath
     * @param @return 设定文件
     * @return 返回类型：boolean
     * @throws
     * @Title: GenerateImage
     * @Description: 该方法的主要作用：// 对字节数组字符串进行Base64解码并生成图片,并上传至服务器
     */
    public boolean GenerateImage(String imgStr, File file) {
        // 图像数据为空
        if (imgStr == null) {
            return false;
        } else {
            @SuppressWarnings("restriction")
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                // Base64解码
                @SuppressWarnings("restriction")
                byte[] bytes = decoder.decodeBuffer(imgStr);
                for (int i = 0; i < bytes.length; ++i) {
                    if (bytes[i] < 0) {
                        bytes[i] += 256;
                    }
                }
                // 生成jpeg图片
                if (!file.exists()) {
                    file.getParentFile().mkdir();
                    OutputStream out = new FileOutputStream(file);
                    out.write(bytes);
                    out.flush();
                    out.close();
                    return true;
                }

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    /**
     * @param @param client 设定文件
     * @return 返回类型：void
     * @throws
     * @Title: facesetAddUser
     * @Description: 该方法的主要作用：人脸注册,给人脸库中注册一个人脸
     */
    public Integer facesetAddUser(AipFace client, String faceBase, String phone) {
        // 参数为数据库中注册的人脸
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", "user's info");
        JSONObject res = client.addUser(faceBase, "BASE64", "test", "face"+phone, options);
        System.out.println(res.toString(2));
        return (Integer) res.get("error_code");
    }
}
